import {reactive, ref, computed, onMounted, h} from "vue";
import {listSmain, addSmain, updateSmain, deleteSmain} from "@/api/mpz/smain";
import {type PaginationProps} from "@pureadmin/table";
import {message} from "@/utils/message";
import {type SmainFormItemProps} from "./types";
import {addDialog} from "@/components/ReDialog";
import editForm from "../form.vue";

export function useSmainForList() {

    const addFormRefSmain = ref();

    /**
     * 查询表单
     */
    const loadingSmain = ref(true);
    const searchFormSmain = reactive({
        id: undefined,
        name: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        pageNo: 1,
        pageSize: 10
    });


    /**
     * 列表
     */
    const paginationSmain = reactive<PaginationProps>({
        total: 0,
        pageSize: 10,
        currentPage: 1,
        background: true
    });

    const smainColumns: TableColumnList = [
        {
            label: "${column.comment}",
            prop: "id",
            width: 70,
            fixed: "left"
        },
        {
            label: "名字",
            prop: "name",
            width: 70,
            fixed: "left"
        },
        {
            label: "创建人",
            prop: "createBy",
            width: 70,
            fixed: "left"
        },
        {
            label: "创建时间",
            prop: "createTime",
            width: 70,
            fixed: "left"
        },
        {
            label: "修改人",
            prop: "updateBy",
            width: 70,
            fixed: "left"
        },
        {
            label: "修改时间",
            prop: "updateTime",
            width: 70,
            fixed: "left"
        },
    ];

    const smainDataList = ref([]);

    async function onSearchSmain() {
        loadingSmain.value = true;
        for (const key in searchFormSmain) {
            if (Object.prototype.hasOwnProperty.call(searchFormSmain, key)) {
                const element = searchFormSmain[key];
                if ("" == searchFormSmain[key] && searchFormSmain[key].length == 0) {
                    searchFormSmain[key] = undefined;
                }
            }
        }
        const {data} = await listSmain(searchFormSmain);
        smainDataList.value = data.records;
        paginationSmain.total = data.totalNum;

        setTimeout(() => {
            loadingSmain.value = false;
        }, 500);
    }

    const resetSearchFormSmain = formEl => {
        if (!formEl) return;
        formEl.resetFields();
        onSearchSmain();
    };

    onMounted(() => {
        onSearchSmain();
    });


    function handleSizeChangeSmain(val: number) {
        console.log(`${val} items per page`);
        searchFormSmain.pageSize = val;
        onSearchSmain();
    }

    function handleCurrentChangeSmain(val: number) {
        console.log(`current page: ${val}`);
        searchFormSmain.pageNo = val;
        onSearchSmain();
    }

    function handleSelectionChangeSmain(val) {
        console.log("handleSelectionChange", val);
        debugger;
    }

    function handleDeleteSmain(row) {
        deleteSmain(row.id).then(res => {
            if (res.code == 0) {
                message(`数据删除成功`, {
                    type: "success"
                });
                onSearchSmain(); // 刷新表格数据
            } else {
                message(`数据删除失败`, {
                    type: "error"
                });
            }
        });
    }


    function openDialogSmain(title = "新增", row?: SmainFormItemProps) {
        addDialog({
            title: `${title}指标对象`,
            props: {
                formInline: {
                    id: row?.id ?? undefined,
                    name: row?.name ?? undefined,
                    createBy: row?.createBy ?? undefined,
                    createTime: row?.createTime ?? undefined,
                    updateBy: row?.updateBy ?? undefined,
                    updateTime: row?.updateTime ?? undefined,
                }
            },
            width: "40%",
            draggable: true,
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(editForm, {ref: addFormRefSmain}),
            beforeSure: (done, {options}) => {
                const FormRef = addFormRefSmain.value.getRef();
                const curData = options.props.formInline as SmainFormItemProps;

                function addData() {
                    addSmain(curData).then(res => {
                        if (res.code == 0) {
                            message(`数据新增成功`, {
                                type: "success"
                            });
                            done(); // 关闭弹框
                            onSearchSmain(); // 刷新表格数据
                        } else {
                            message(`数据新增失败`, {
                                type: "error"
                            });
                        }
                    });
                }

                function handleUpdate(curData) {
                    updateSmain(curData).then(res => {
                        if (res.code == 0) {
                            message(`数据修改成功`, {
                                type: "success"
                            });
                            done(); // 关闭弹框
                            onSearchSmain(); // 刷新表格数据
                        } else {
                            message(`数据修改失败`, {
                                type: "error"
                            });
                        }
                    });
                }

                FormRef.validate(valid => {
                    debugger
                    if (valid) {
                        console.log("curData", curData);
                        // 表单规则校验通过
                        if (title === "新增") {
                            // 实际开发先调用新增接口，再进行下面操作
                            addData();
                        } else {
                            // 实际开发先调用编辑接口，再进行下面操作
                            handleUpdate(curData);
                        }
                    }
                });
            }
        });
    }

    return {
        loadingSmain,
        searchFormSmain,
        paginationSmain,
        smainColumns,
        smainDataList,
        onSearchSmain,
        resetSearchFormSmain,
        handleDeleteSmain,
        handleSizeChangeSmain,
        handleCurrentChangeSmain,
        handleSelectionChangeSmain,
        openDialogSmain
    };
}
